package com.leapp.sk.ui.activity.personal

import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.view.View
import cc.vv.lkbasecomponent.http.LKHttp
import cc.vv.lkbasecomponent.http.lib.setting.Settings
import cc.vv.lkbasecomponent.util.LKDateTimeUtil
import cc.vv.lkbasecomponent.util.LKSPUtil
import cc.vv.lklibrary.http.base.okhttpfactory.plugins.httpplugin.MediaTypeWrap
import com.example.baselibrary.util.LKToastUtil
import com.example.mvp.activity.BaseActivityMVP
import com.example.mvp.binder.BaseDataBinder
import com.example.mvp.view.TimePicker.OnDateSetListener
import com.example.mvp.view.TimePicker.TimePickerDialog
import com.example.mvp.view.imgselector.ImageSelector
import com.example.util.FileSizeUtil
import com.example.util.MD5
import com.example.util.addYear
import com.leapp.sk.R
import com.leapp.sk.app.*
import com.leapp.sk.bean.request.login.UPFileRequestEntity
import com.leapp.sk.bean.request.login.UpdatePersonalInfoRequestEntity
import com.leapp.sk.bean.request.personal.MineRequestEntity
import com.leapp.sk.bean.response.login.UPFileResponseEntity
import com.leapp.sk.bean.response.login.UpdatePersonalInfoResponseEntity
import com.leapp.sk.bean.response.personal.PersonalInfoResponseEntity
import com.leapp.sk.binder.BaseBinder
import com.leapp.sk.inter.ChangePhoneInterface
import com.leapp.sk.inter.ChangerSexInterface
import com.leapp.sk.inter.ImageHeadPathInterface
import com.leapp.sk.sever.login.PrefectUserInfoSever
import com.leapp.sk.sever.personal.PersonalDataSever
import com.leapp.sk.util.ChangePhoneInterfaceUtils
import com.leapp.sk.util.HeadImageCropUtil
import com.example.util.finallist.*
import com.leapp.sk.viewdelegate.personal.PersonalDataDelegate
import java.io.File
import java.io.IOException

/**
 * 个人资料
 * @author  chaohaipeng  on 2018/8/8.
 */
class PersonalDataActivity :BaseActivityMVP<PersonalDataDelegate>(), OnDateSetListener, ImageHeadPathInterface , ChangePhoneInterface,ChangerSexInterface {
    override fun getSex(sex: Int) {
       this.sex=sex
        httpUpdateData()
        LKSPUtil.getInstance().put(KEY_SEX,sex)

    }
    /**
     * 头像地址
     */
    private var headUrl: String? = ""
    /**
     * 性别
     */
    private var sex: Int = 0
    override fun getPhone(phone: String) {
        viewDelegate.setPhone(phone)
    }
    /**
     * 时间选择器
     */
    private var mPickerDialog: TimePickerDialog? = null
    override fun initDate() {
        initSeleteDate()
        httpMine()
    }
    override fun bindEvenListener() {
        ChangePhoneInterfaceUtils.getInstance().setChangePhoneInterface(this)
        viewDelegate.setOnClickListener(View.OnClickListener {
            pickImage()
        },R.id.rl_apd_head)
        viewDelegate.setOnClickListener(View.OnClickListener {
            val intent=Intent(this,SettingNickActivity::class.java)
            intent.putExtra(SETTING_NICK,viewDelegate.getNick())
            startActivityForResult(intent, CODE_204)
        },R.id.rl_apd_nick)
//        viewDelegate.setOnClickListener(View.OnClickListener {
//            val intent=Intent(this,ChangePhoneActivity::class.java)
//            intent.putExtra(CHANGE_PHONE,viewDelegate.getPhone())
//            startActivity(intent)
//        },R.id.rl_apd_personal_phone)

        viewDelegate.setOnClickListener(View.OnClickListener {
            viewDelegate.initSexDialog(this)
        },R.id.rl_apd_personal_sex)

        viewDelegate.setOnClickListener(View.OnClickListener {
             val intent=Intent(this,PersonalIntroduceActivity::class.java)
            intent.putExtra(PERSONAL_INTRODUCE,viewDelegate.getIntroduce())
               startActivityForResult(intent, CODE_203)
        },R.id.rl_apd_personal_introduce)
        viewDelegate.setOnClickListener(View.OnClickListener {
            mPickerDialog?.show(fragmentManager, "info")
        },R.id.rl_apd_personal_brith)
    }
    override fun getDelegateClass(): Class<PersonalDataDelegate> {
        return PersonalDataDelegate::class.java
    }
    override fun getDataBinder(): BaseDataBinder<*, *> {
        return BaseBinder()
    }
    override fun initView(p0: Bundle?) {
        viewDelegate.setTitle(resources.getString(R.string.string_personal_zl))
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        HeadImageCropUtil.getResultHeadFile(requestCode, resultCode, data, this, this)
        when(requestCode){
            CODE_203->{
                if(requestCode== CODE_203){
                    val stringExtra = data?.getStringExtra(PERSONAL_INTRODUCE)
                    viewDelegate?.setIntroduce(stringExtra)
                }
            }
            CODE_204->{
                if(requestCode== CODE_204){
                    val stringExtra = data?.getStringExtra(SETTING_NICK)
                    viewDelegate?.setNick(stringExtra)
                }
            }
        }
    }
    override fun onDateSet(timePickerView: TimePickerDialog?, millseconds: Long) {
        val timeData = LKDateTimeUtil.formatDateTime(millseconds, "yyyy-MM-dd")
        viewDelegate.setBrith(timeData)
        httpUpdateData()
    }

    override fun getImageHeadFile(file: File?) {
        httpUpFile(file)
      //  viewDelegate.setHeadData(file?.absolutePath)

    }
    /**
     * 初始化时间选择器
     */
    private fun initSeleteDate() {
        var tenYears = addYear(-5)
        var endYears = addYear(5)
        mPickerDialog = TimePickerDialog.Builder()
                .setCallBack(this)
                .setCyclic(false)
                .setMinMillseconds(tenYears)
                .setThemeColor(ContextCompat.getColor(this, R.color.color_E0E0E0))
                .setTitleStringId(resources.getString(R.string.string_time_chose_title))
                .setWheelItemTextNormalColor(ContextCompat.getColor(this, R.color.color_A3A5A8))
                .setWheelItemTextSelectorColor(ContextCompat.getColor(this, R.color.color_474747))
                .setWheelItemTextSize(15)
                .setMaxMillseconds(endYears)
                .setVisiblesYMD(true)
                .setCurrentMillseconds(System.currentTimeMillis())
                .build()
    }
    /**
     * 头像选择
     */
    private fun pickImage() {
        ImageSelector.getInstance()
                .setSelectModel(ImageSelector.MULTI_MODE)
                .setMaxCount(1)
                .setGridColumns(3)
                .setShowCamera(true)
                .startSelect(this)
    }

    /**
     * 获取个人信息
     */
    private fun httpMine() {
        val baseRequestEntity = MineRequestEntity()
        baseRequestEntity.id=baseRequestEntity.userId
        LKHttp.post(PERSONAL_INFO, baseRequestEntity, PersonalInfoResponseEntity::class.java, object : BaseCallBack<PersonalInfoResponseEntity>(this) {
            override fun onSuccess(url: String?, resultText: String?, obj: PersonalInfoResponseEntity?) {
                super.onSuccess(url, resultText, obj)
                if (obj?.code == SKCODE_200) {
                    PersonalDataSever.getInstance().binderData(this@PersonalDataActivity,viewDelegate,obj)
                    if(!TextUtils.isEmpty(headUrl!!)){
                        LKSPUtil.getInstance().put(KEY_AVATAR,headUrl!!)
                    }


                }else{
                    LKToastUtil.showToastShort(obj?.message)
                }
            }
            override fun onFailure(url: String?, isLoading: Boolean, exceptionStr: String?) {
                super.onFailure(url, isLoading, exceptionStr)
                LKToastUtil.showToastShort(resources.getString(R.string.app_net_erro))
            }
        }
                , true, Settings(MediaTypeWrap.MEDIA_TYPE_FORM))

    }

    /**
     * 更新数据
     */
    private fun httpUpdateData() {
        val updatePersonalInfoRequestEntity = UpdatePersonalInfoRequestEntity()
        updatePersonalInfoRequestEntity.avatar =headUrl!!
        updatePersonalInfoRequestEntity.birthday=viewDelegate.getBrith()
        updatePersonalInfoRequestEntity.sex=sex
        LKHttp.post(UPDATE_PERSONAL_INFO, updatePersonalInfoRequestEntity, UpdatePersonalInfoResponseEntity::class.java, object : BaseCallBack<UpdatePersonalInfoResponseEntity>(this) {
            override fun onSuccess(url: String?, resultText: String?, obj: UpdatePersonalInfoResponseEntity?) {
                super.onSuccess(url, resultText, obj)
                if (obj?.code == SKCODE_200) {
                 if(!TextUtils.isEmpty(headUrl!!)){
                     LKSPUtil.getInstance().put(KEY_AVATAR,headUrl!!)

                 }
                } else {
                    LKToastUtil.showToastShort(obj?.message)
                }
            }
            override fun onFailure(url: String?, isLoading: Boolean, exceptionStr: String?) {
                super.onFailure(url, isLoading, exceptionStr)
                LKToastUtil.showToastShort(resources.getString(R.string.app_net_erro))
            }
        }
                , true, Settings(MediaTypeWrap.MEDIA_TYPE_FORM))
    }

    /**
     * 上传文件
     */
    private fun httpUpFile(file: File?) {
        if (file == null) {
            return
        }
        val upFileRequestEntity = UPFileRequestEntity()
        upFileRequestEntity.appKey = "leapp_sk"
        upFileRequestEntity.ext = FileSizeUtil.getInstance().getFileHname(file.absolutePath)
        upFileRequestEntity.file = file
        try {
            upFileRequestEntity.md5 = (MD5.md5(file))
        } catch (e: IOException) {
            e.printStackTrace()
        }
        upFileRequestEntity.fileSize = FileSizeUtil.getInstance().getFileOrFilesIntSize(file.absolutePath, FileSizeUtil.SIZETYPE_KB)
        LKHttp.upLoad(UP_FILE, upFileRequestEntity, UPFileResponseEntity::class.java, object : BaseCallBack<UPFileResponseEntity>(this) {
            override fun onSuccess(url: String?, resultText: String?, obj: UPFileResponseEntity?) {
                super.onSuccess(url, resultText, obj)
                if (obj?.statusCode == SKCODE_200) {
                    headUrl = PrefectUserInfoSever.getInstance().getUrl(obj)
                    viewDelegate?.setHeadData(headUrl)
                    httpUpdateData()
                } else {
                    LKToastUtil.showToastShort(obj?.statusMessage)
                }
            }
            override fun onFailure(url: String?, isLoading: Boolean, exceptionStr: String?) {
                super.onFailure(url, isLoading, exceptionStr)
                LKToastUtil.showToastShort(resources.getString(R.string.app_net_erro))
            }
        }
                , true, Settings(MediaTypeWrap.MEDIA_TYPE_FORM))

    }


}